package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.stream.CollectorUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.query.album.AlbumInfoQuery;
import com.atguigu.tingshu.vo.album.AlbumAttributeValueVo;
import com.atguigu.tingshu.vo.album.AlbumInfoVo;
import com.atguigu.tingshu.vo.album.AlbumListVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private BaseAttributeMapper baseAttributeMapper;
    @Autowired
    private AlbumInfoMapper albumInfoMapper;
    @Autowired
    private AlbumAttributeValueMapper albumAttributeValueMapper;
    @Autowired
    private AlbumStatMapper albumStatMapper;


    @Override
    public List<JSONObject> getBaseCategoryList() {
        List<BaseCategoryView> baseCategoryViews = baseCategoryViewMapper.selectList(null);
        //组别分类 一级分类
        List<JSONObject> jsonObjectList = new ArrayList<>();

        Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        if (CollectionUtil.isNotEmpty(category1Map)) {
            jsonObjectList = category1Map.entrySet().stream().map(entry1 -> {
                Long key = entry1.getKey();
                String category1Name = entry1.getValue().get(0).getCategory1Name();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("categoryId", key);
                jsonObject.put("categoryName", category1Name);

                Map<Long, List<BaseCategoryView>> category2Map = entry1.getValue().stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
                if (CollectionUtil.isNotEmpty(category2Map)) {
//                    List<JSONObject> jsonObject2List = new ArrayList<>();
                    List<JSONObject> jsonObject2List = category2Map.entrySet().stream().map(entry2 -> {
                        Long key2 = entry2.getKey();
                        String category2Name = entry2.getValue().get(0).getCategory2Name();
                        JSONObject jsonObject2 = new JSONObject();
                        jsonObject2.put("categoryId", key2);
                        jsonObject2.put("categoryName", category2Name);
                        Stream<JSONObject> jsonObject3List = entry2.getValue().stream().map(entry3 -> {
                            JSONObject jsonObject3 = new JSONObject();
                            jsonObject3.put("categoryId", entry3.getCategory3Id());
                            jsonObject3.put("categoryName", entry3.getCategory3Name());
                            return jsonObject3;
                        });
                        jsonObject2.put("categoryChild", jsonObject3List);
                        return jsonObject2;
                    }).collect(Collectors.toList());
                    jsonObject.put("categoryChild", jsonObject2List);
                }
                return jsonObject;
            }).collect(Collectors.toList());

        }
        return jsonObjectList;
    }

    /**
     * 保存专辑
     * /api/album/albumInfo/saveAlbumInfo
     *
     * @param albumInfoVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void albumInfoBySaveAlbumInfo(AlbumInfoVo albumInfoVo) {
        AlbumInfo albumInfo = BeanUtil.copyProperties(albumInfoVo, AlbumInfo.class);
        albumInfo.setUserId(AuthContextHolder.getUserId());
        albumInfo.setIncludeTrackCount(0);
        albumInfo.setIsFinished("0");
        albumInfo.setTracksForFree(5);
        albumInfo.setStatus(SystemConstant.ALBUM_STATUS_PASS);
        albumInfoMapper.insert(albumInfo);
        System.out.println(albumInfo);
        //2.保存专辑标签关系
        //2.1 将提交专辑标签关系VO集合转为PO集合
        List<AlbumAttributeValueVo> albumAttributeValueVoList = albumInfoVo.getAlbumAttributeValueVoList();
        if (CollectionUtil.isNotEmpty(albumAttributeValueVoList)) {
            for (AlbumAttributeValueVo albumAttributeValueVo : albumAttributeValueVoList) {
                AlbumAttributeValue albumAttributeValue = BeanUtil.copyProperties(albumAttributeValueVo, AlbumAttributeValue.class);
                albumAttributeValue.setAlbumId(albumInfo.getId());
                System.out.println(albumAttributeValue);
                albumAttributeValueMapper.insert(albumAttributeValue);
            }
        }

        Long albumId = albumInfo.getId();
        this.saveAlbum(albumId, SystemConstant.ALBUM_STAT_PLAY, 0);
        this.saveAlbum(albumId, SystemConstant.ALBUM_STAT_SUBSCRIBE, 0);
        this.saveAlbum(albumId, SystemConstant.ALBUM_STAT_BUY, 0);
        this.saveAlbum(albumId, SystemConstant.ALBUM_STAT_COMMENT, 0);

    }

    private void saveAlbum(Long albumId, String albumStatPlay, int statNum) {
        AlbumStat albumStat = new AlbumStat();
        albumStat.setAlbumId(albumId);
        albumStat.setStatType(albumStatPlay);
        albumStat.setStatNum(statNum);
        albumStatMapper.insert(albumStat);
    }


    /**
     * 根据一级分类Id获取分类（标签名包含标签值） 列表
     * /api/album/category/findAttribute/{category1Id}
     *
     * @param category1Id
     * @return
     */
    @Override
    public List<BaseAttribute> findAttributeByCategory1Id(Long category1Id) {
        List<BaseAttribute> baseAttributes = baseAttributeMapper.selectAttributeByCategory1Id(category1Id);
        return baseAttributes;
    }

    /**
     * api/album/albumInfo/findUserAlbumPage/{page}/{limit}
     *
     * @param pageInfo
     * @param albumInfoQuery
     * @return
     */
    @Override
    public Page<AlbumListVo> findUserAlbumPage(Page<AlbumListVo> pageInfo, AlbumInfoQuery albumInfoQuery) {
        return albumInfoMapper.getUserAlbumPage(pageInfo, albumInfoQuery);
    }

    /**
     * 根据ID删除专辑
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeAlbumInfoByid(Long id) {
        //判断专辑下是否有声音
        AlbumInfo albumInfo = albumInfoMapper.selectById(id);
        if (albumInfo.getIncludeTrackCount() != 0) {
            throw new GuiguException(400, "专辑下还有声音删除错误");
        }
        //1.删除专辑信息
        albumInfoMapper.deleteById(id);
        //2.删除专辑统计表
        QueryWrapper<AlbumStat> albumStatQueryWrapper = new QueryWrapper<>();
        albumStatQueryWrapper.eq("album_id", id);
        albumStatMapper.delete(new QueryWrapper<AlbumStat>().eq("album_id", id));
        //3.删除专辑属性 - 值表
        albumAttributeValueMapper.delete(new QueryWrapper<AlbumAttributeValue>().eq("album_id", id));
    }

    /**
     * 根据ID查询专辑信息
     * @param id
     * @return
     */
    @Override
    public AlbumInfo getAlbumInfo(Long id) {
        //获取专辑信息
        AlbumInfo albumInfo = albumInfoMapper.selectById(id);
        //获取专辑值信息
//		BeanUtil.isNotEmpty(albumInfo);
        if (albumInfo != null) {
            List<AlbumAttributeValue> albumAttributeValues = albumAttributeValueMapper.selectList(new QueryWrapper<AlbumAttributeValue>().eq("album_id", id));
            albumInfo.setAlbumAttributeValueVoList(albumAttributeValues);
        }
        return albumInfo;
    }

    /**
     * 修改专辑
     * @param id
     * @param albumInfoVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAlbumInfoById(Long id, AlbumInfoVo albumInfoVo) {
        //专辑表
        AlbumInfo albumInfo = BeanUtil.copyProperties(albumInfoVo, AlbumInfo.class);
        albumInfo.setId(id);
        albumInfo.setEstimatedTrackCount(0);
        albumInfo.setStatus(SystemConstant.ALBUM_STATUS_PASS);
        albumInfo.setUpdateTime(new Date());
        albumInfoMapper.updateById(albumInfo);
        // 属性值
        //删除
        albumAttributeValueMapper.delete(new QueryWrapper<AlbumAttributeValue>().eq("album_id", id));

        List<AlbumAttributeValueVo> albumAttributeValueVoList = albumInfoVo.getAlbumAttributeValueVoList();
        if (CollectionUtil.isNotEmpty(albumAttributeValueVoList)) {
            for (AlbumAttributeValueVo albumAttributeValueVo : albumAttributeValueVoList) {
                AlbumAttributeValue albumAttributeValue = BeanUtil.copyProperties(albumAttributeValueVo, AlbumAttributeValue.class);
                albumAttributeValue.setAlbumId(id);
                albumAttributeValue.setUpdateTime(new Date());
                albumAttributeValueMapper.insert(albumAttributeValue);
            }
        }
    }

    /**
     * 根据三级分类Id 获取到分类信息
     *
     * @param category3Id
     * @return
     */
    @Override
    public BaseCategoryView getCategoryView(Long category3Id) {
        LambdaQueryWrapper<BaseCategoryView> baseCategoryViewLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseCategoryViewLambdaQueryWrapper.eq(BaseCategoryView::getCategory3Id, category3Id);
        BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectOne(baseCategoryViewLambdaQueryWrapper);
        return baseCategoryView;
    }

    /**
     * 据一级分类Id查询三级分类列表
     * @param category1Id
     * @return
     */
    @Override
    public List<BaseCategory3> findTopBaseCategory3(Long category1Id) {
        //获取二级分类
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id", category1Id));

        //获取三级分类
        List<Long> baseCategory2Ids = baseCategory2List.stream().map(BaseCategory2::getId).collect(Collectors.toList());
        QueryWrapper<BaseCategory3> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_top", 1).in("category2_id", baseCategory2Ids).orderByAsc("order_num").last("limit 7");
        List<BaseCategory3> baseCategory3List = baseCategory3Mapper.selectList(queryWrapper);
        return baseCategory3List;


    }

    /**
     * 根据一级分类id获取全部分类信息
     * @param category1Id
     * @return
     */
    @Override
    public JSONObject getBaseCategorys(Long category1Id) {
        List<JSONObject> baseCategoryList = this.getBaseCategoryList();
        for (JSONObject jsonObject : baseCategoryList) {
            Long categoryId1 = (Long) jsonObject.get("categoryId");
            if (categoryId1.longValue() == category1Id.longValue()) {
                return jsonObject;
            }
        }
        return null;
    }
}
